package com.zp.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicBoolean;

public class ConnectTask implements ConnectServer {

    private AtomicBoolean connected = new AtomicBoolean(false);


    public static EventLoopGroup  nioGroup = new NioEventLoopGroup();

    private Bootstrap bootstrap;

    private Channel channel;

    public ConnectTask() {
        //处理读写io操作


        bootstrap = new Bootstrap();

        bootstrap.group(nioGroup);

        bootstrap.channel(NioSocketChannel.class);

        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new StringEncoder());
                ch.pipeline().addLast(new StringDecoder());
                ch.pipeline().addLast(new HelloClientHandler());
            }
        });


    }

    @Override
    public void connect(String host, int port) {

        try {
            ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)).sync();
            channel = future.channel();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() {
        nioGroup.shutdownGracefully();
    }

    @Override
    public Channel connectServerChannel() {
        return channel;
    }
}
